//
//  SettingTableViewController.m
//  MingShi
//
//  Created by MJiao on 15/7/15.
//  Copyright (c) 2015年 MJiao. All rights reserved.
//

#import <mach-o/loader.h>
#import "SettingTableViewController.h"
#import "CommonUtils.h"
#import "KVNProgress.h"
#import "ModifyProfileTableViewController.h"
#import "UserManager.h"
#import "MobClick.h"
#import "AFHTTPRequestOperationManager.h"

enum {
    CleanCache,
    LoginOut
} HandleType;

@interface SettingTableViewController ()

@end

@implementation SettingTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app版本
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    // app build版本
    // NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
    [self.lbApplicationVersion setText:app_Version];

    [self assembleLbCacheSize];

    User *user = [[UserManager shareUserManager] curUser];
    if (user.userId == -1) {
        [self.btnExitCurrAccountAction setHidden:YES];
    }

}

- (void)assembleLbCacheSize {
    float cacheSize = [CommonUtils getApplicationCacheSize];
    [self.lbCacheSize setText:[NSString stringWithFormat:@"%1.2fM", cacheSize]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// Called when a button is clicked. The view will be automatically dismissed after this call returns
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

    //取消上次选择中的被选择效果
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:NO];

    if (buttonIndex != 0) {
        return;
    }
    if (self.handleType == LoginOut) {
        [[UserManager shareUserManager] loginOutCurrentAccount];
        [self.btnExitCurrAccountAction setHidden:YES];
        [self.navigationController popToRootViewControllerAnimated:YES];
    } else {
        [self clearApplicationCache];
    }
}

//清除缓存
- (void)clearApplicationCache {
    dispatch_async(
            dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];

                NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
//                       NSLog(@"files :%d",[files count]);
                for (NSString *p in files) {
                    NSError *error;
                    NSString *path = [cachPath stringByAppendingPathComponent:p];
                    if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                        [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
                    }
                }
        [self performSelectorOnMainThread:@selector(clearCacheSuccess) withObject:nil waitUntilDone:YES];
    });

}

- (void)clearCacheSuccess {
    NSLog(@"清除缓存");
    [self assembleLbCacheSize];
}

// 将字典或者数组转化为JSON串
- (NSData *)toJSONData:(id)theData {

    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];

    if ([jsonData length] > 0 && error == nil) {
        return jsonData;
    } else {
        return nil;
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    //取消上次选择中的被选择效果
    [self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:NO];
    long section = [indexPath section];
    long row = [indexPath row];
    if (section == 1) {
        switch (row) {
            case 0: {
                NSString *string = @"您确定要清除缓存吗";
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:string delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
                alert.alertViewStyle = UIAlertViewStyleDefault;
                [alert show];
            }
                break;
            case 1: {
                /**
                *  检查更新
                */
                [MobClick checkUpdate];

                // [MobClick checkUpdateWithDelegate:self selector:@selector(appUpdate:)];
            }
                break;
        }

    }
    //退出当前账号


}

- (void)appUpdate:(NSDictionary *)appInfo {
    NSLog(@"appUpdate%@", appInfo);

    BOOL update = appInfo && [appInfo objectForKey:@"update"] && [appInfo objectForKey:@"update"] && [[appInfo objectForKey:@"update"] boolValue];
    if (!update) {
        [KVNProgress showWithStatus:@"当前已是最新版"];
    }

}
- (IBAction)btnLoginOutCurrAccountAction:(id)sender {
    // NSLog(@"---btnLoginOutCurrAccountAction-----");
    User *user = [[UserManager shareUserManager] curUser];
    NSString *string = [NSString stringWithFormat:@"您确定要退出账号%@存吗", user.account];

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:string delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    alert.alertViewStyle = UIAlertViewStyleDefault;
    [alert show];

    self.handleType = LoginOut;
}

@end
